package com.atguigu.sink;

import com.atguigu.bean.WaterSensor;
import com.atguigu.function.WaterSensorFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.connector.jdbc.*;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;

import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author yhm
 * @create 2024-04-03 14:36
 */
public class Test04_MysqlSink {
    public static void main(String[] args) throws Exception {
        // 1. 创建环境
        Configuration conf = new Configuration();
        conf.setInteger("rest.port",8081);

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        // 2. 读取数据源
        DataStreamSource<String> streamSource = env.socketTextStream("hadoop102", 7777);


        // 3. 处理数据
        SingleOutputStreamOperator<WaterSensor> beanStream = streamSource.flatMap(new WaterSensorFunction());

        // 4. 输出
        SinkFunction<WaterSensor> sinkFunction = JdbcSink.<WaterSensor>sink(
                "insert into ws values(?,?,?)", new JdbcStatementBuilder<WaterSensor>() {
                    @Override
                    public void accept(PreparedStatement preparedStatement, WaterSensor waterSensor) throws SQLException {
                        preparedStatement.setObject(1,waterSensor.id);
                        preparedStatement.setObject(2,waterSensor.ts);
                        preparedStatement.setObject(3,waterSensor.vc);
                    }
                }
        ,new JdbcExecutionOptions.Builder()// 执行配置
                        .withMaxRetries(3)// 重试次数
                        .withBatchSize(100)// 批次大小
                        .withBatchIntervalMs(3000L)//等待时间
                        .build(),
                new JdbcConnectionOptions.JdbcConnectionOptionsBuilder()
                        .withUrl("jdbc:mysql://hadoop102:3306/test?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8")
                        .withUsername("root")
                        .withPassword("000000")
                        .withConnectionCheckTimeoutSeconds(60)
                        .build());

        beanStream.addSink(sinkFunction);

        // 5. 执行环境
        env.execute();
    }
}
